﻿using System;
using System.IO;
using System.Collections.ObjectModel;
using System.Diagnostics;
using VioletDevelopmentLaboratory.Net.Web.Configuration;

namespace VioletDevelopmentLaboratory.Net.Web
{
	public class ExceptionLogFile
	{
		private static String logFolder = Path.Combine(VUtility.WebApplicationPhysicalPath, VWebConfigurationReader.Path.ExceptionLogFolder);

		public static void Delete(String fileName)
		{
			File.Delete(Path.Combine(logFolder, fileName));
		}

		private static String getExceptionString(Exception exception)
		{
			String message = "";
			message = message + "#Time :\r\n" + DateTime.Now + "\r\n#Source :\r\n" + exception.Source + "\r\n#TargetSite :\r\n" + exception.TargetSite + "\r\n#Message :\r\n" + exception.Message + "\r\n#StackTrace :\r\n" + exception.StackTrace + "\r\n#HelpLink :\r\n" + exception.HelpLink + "\r\n\r\n";

			if (exception.InnerException != null)
			{
				message = message + getExceptionString(exception.InnerException);
			}
			return message;
		}

		public static ExceptionLogFileCollection GetLogs()
		{
			ExceptionLogFileCollection logs = new ExceptionLogFileCollection();
			ExceptionLogFile log = null;
			FileInfo logFile = null;
			StreamReader logFileReader = null;
			foreach (String fileName in Directory.GetFiles(logFolder, "*.txt", SearchOption.TopDirectoryOnly))
			{
				logFile = new FileInfo(fileName);
				logFileReader = logFile.OpenText();
				log = new ExceptionLogFile();
				log.fileName = logFile.Name;
				log.creationTime = logFile.CreationTime;
				log.detailInfo = logFileReader.ReadToEnd();
				logFileReader.Close();
				logs.Add(log);
			}
			return logs;
		}

		public static void Write(Exception exception)
		{
			if (exception == null)
			{
				throw new ArgumentNullException("ex");
			}
			TextWriterTraceListener exceptionLog = new TextWriterTraceListener(Path.Combine(logFolder, DateTime.Now.Ticks + ".txt"));
			exceptionLog.WriteLine(getExceptionString(exception));
			exceptionLog.Close();
			exceptionLog.Dispose();
		}

		private DateTime creationTime;
		public DateTime CreationTime { get { return this.creationTime; } }

		private String detailInfo;
		public String DetailInfo { get { return this.detailInfo; } }

		private String fileName;
		public String FileName { get { return this.fileName; } }
	}

	public class ExceptionLogFileCollection : Collection<ExceptionLogFile> { }
}
